package com.centerm.bluetooth.lklcommon.controller;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.centerm.bluetooth.core.controller.BaseController;
import com.centerm.bluetooth.core.controller.constants.WaitEnum;
import com.centerm.bluetooth.ibridge.BluetoothIBridgeDevice;
import com.centerm.bluetooth.lklcommon.Command;
import com.centerm.bluetooth.lklcommon.listener.IPBOCListener;
import com.centerm.bluetooth.lklcommon.mode.Track;
import com.centerm.bluetooth.model.Respond;
import com.centerm.util.HexUtil;
import com.centerm.util.Logger;
import com.centerm.util.TlvUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by linwenhui on 2017/5/16.
 */

public class PBOCController extends BaseController<IPBOCListener> {

    public PBOCController(@NonNull Context context) {
        super(context);
    }

    protected byte[] buildPBOCTlv(String money) throws IOException {
        if (TextUtils.isEmpty(money)) {
            money = "00";
        } else {
            money = String.format("%12s", money).replace(" ", "0");
        }
        Map<String, String> map = new HashMap<>();
        map.put("9F02", money);
        map.put("9F03", "000000000000");
        map.put("9C", "00");
        map.put("DF7C", "01");
        map.put("DF71", "06");
        map.put("DF72", "01");
        map.put("DF73", "00");
        byte[] tlvData = TlvUtil.mapToTlv(map);
        Logger.i(" == buildPBOCTlv == ");
        Logger.i(HexUtil.byte2HexStr(tlvData));
        int paramLen = tlvData.length;//IC卡数据数据长度
        byte[] paramLenBytes = HexUtil.toLen(paramLen);
        ByteArrayOutputStream params = new ByteArrayOutputStream();
        params.write(paramLenBytes);
        params.write(tlvData);
        byte[] datas = params.toByteArray();
        params.close();
        return datas;
    }

    public boolean startPBOC(String money) throws IOException {

        if (wait != WaitEnum.FREE)
            return false;
        boolean res = send(Command.PBOC, buildPBOCTlv(money));
        if (res)
            setTimeOut(DEFAULT_TIMEOUT);
        return res;
    }

    public boolean startQPBOC(String money) throws IOException {

        if (wait != WaitEnum.FREE)
            return false;

        boolean res = send(Command.QPBOC, buildPBOCTlv(money));
        if (res)
            setTimeOut(DEFAULT_TIMEOUT);
        return res;
    }

    public boolean endPBOC(int result) throws IOException {

        if (wait != WaitEnum.FREE)
            return false;

        byte[] params = new byte[]{(byte) result};
        boolean res = send(Command.END_PBOC, params);
        if (res)
            setTimeOut(DEFAULT_TIMEOUT);
        return res;
    }

    @Override
    public void onDataReceived(BluetoothIBridgeDevice device, Respond respond) {
        super.onDataReceived(device, respond);
        String cmdString = HexUtil.byte2HexStr(respond.getCmd()).toUpperCase();
        if (Command.PBOC_STRING.equals(cmdString)) {
            byte[] datas = new byte[respond.getContent().length - 2];
            System.arraycopy(respond.getContent(), 2, datas, 0, datas.length);
            parsePBOCResult(datas);
        } else if (Command.QPBOC_STRING.equals(cmdString)) {
            byte[] datas = new byte[respond.getContent().length - 2];
            System.arraycopy(respond.getContent(), 2, datas, 0, datas.length);
            parsePBOCResult(datas);
        } else if (Command.END_PBOC_STRING.equals(cmdString)) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (baseListener != null)
                baseListener.onEndPBOC();
        }
    }

    @Override
    public synchronized void onDataReceivedError(BluetoothIBridgeDevice device, Respond respond) {

        String cmdString = HexUtil.byte2HexStr(respond.getCmd()).toUpperCase();
        if (Command.PBOC_STRING.equals(cmdString) || Command.QPBOC_STRING.equals(cmdString)) {
            cancelTimer();
            if (baseListener != null)
                baseListener.onPBOCError();
        } else
            super.onDataReceivedError(device, respond);
    }

    protected void parsePBOCResult(byte[] datas) {
        Map<String, String> tlvMap = TlvUtil.tlvToMap(datas);
        String executeResult = tlvMap.get("DF75");
        if ("00".equalsIgnoreCase(executeResult) || "01".equalsIgnoreCase(executeResult) || "03".equalsIgnoreCase(executeResult)) {
            String pan = tlvMap.get("5A");
            String twoTD = tlvMap.get("57");
            String serial = tlvMap.get("5734");
            String expireDT = "";
            int index = twoTD.indexOf("D");
            if (index != -1) {
                // 有效期，二磁等效信息 = 后面4位
                expireDT = twoTD.substring(index + 1,
                        index + 5);
            }
            Track track = new Track();
            track.setPan(pan);
            track.setTrack2(twoTD);
            track.setExpire(expireDT);
            track.setCardSerail(serial);
            track.setData55(HexUtil.byte2HexStr(datas));
            if (baseListener != null)
                baseListener.onPBOCSuc(track);
        } else {
            if (baseListener != null)
                baseListener.onPBOCError();
        }
    }
}
